package com.fatmeraid.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fatmeraid.common.exception.FarmException;
import com.fatmeraid.common.login.LoginUser;
import com.fatmeraid.common.login.LoginUserHolder;
import com.fatmeraid.common.result.ResultCodeEnum;
import com.fatmeraid.dao.UserDao;
import com.fatmeraid.domain.User;
import com.fatmeraid.service.UserService;
import com.fatmeraid.common.model.PageResult;
import com.fatmeraid.vo.PaginationVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

	@Autowired
	private UserDao userDao;

	@Override
	public PageResult<User> getUserList(PaginationVo paginationVo) {
		// 1. 校验分页参数（避免null或非法值导致的异常）
		long current = paginationVo.getCurrent() == null ? 1 : paginationVo.getCurrent();
		long size = paginationVo.getSize() == null ? 10 : paginationVo.getSize();
		IPage<User> page = new Page<>(current, size);

		// 2. 处理关键词：去空格，避免无效查询
		String keyword = paginationVo.getKeyword() != null ? paginationVo.getKeyword().trim() : "";

		QueryWrapper<User> queryWrapper = new QueryWrapper<>();

		// 3. 关键词搜索条件（nested包裹OR，确保逻辑独立）
		if (!keyword.isEmpty()) {
			queryWrapper.nested(qw ->
					qw.likeRight("real_name", keyword)  // 若实体类有对应属性，建议用lambda：User::getRealName
							.or().likeRight("phone", keyword) // 同上：User::getPhone
			);
		}

		// 4. 角色类型条件（用nested包裹OR，确保与其他条件用AND关联）
		queryWrapper.nested(qw ->
				qw.eq("role_type", 1)  // 建议用lambda：User::getRoleType
						.or().eq("role_type", 2)
		);

		// 5. 执行分页查询
		IPage<User> userIPage = userDao.selectPage(page, queryWrapper);

		// 6. 构造返回结果
		return new PageResult<>(userIPage.getTotal(), userIPage.getRecords());
	}

	@Override
	public boolean addUser(User user) {
		// 查看当前权限是否为管理员
		LoginUser loginUser = LoginUserHolder.getLoginUser();
		Long userId = loginUser.getUserId();
		if (userDao.selectById(userId).getRoleType()!=3){
			throw new FarmException(ResultCodeEnum.ADMIN_ACCESS_FORBIDDEN);
		}

		// 检查用户名是否已存在
		User existingUser = userDao.selectOneByUsername(user.getUsername());
		if (existingUser != null) {
			throw new FarmException(ResultCodeEnum.ADMIN_USERNAME_ALREADY_EXISTS);
		}


		// 密码加密
		String encryptedPassword = DigestUtils.md5DigestAsHex(
				user.getPassword().getBytes(StandardCharsets.UTF_8)
		);
		user.setPassword(encryptedPassword);

		// 设置默认值
		user.setStatus(1); // 默认为启用状态
		user.setCreateTime(LocalDateTime.now());
		user.setUpdateTime(LocalDateTime.now());

		// 保存用户
		return this.save(user);
	}

	@Override
	public boolean updateUser(User user) {
		// 查看当前权限是否为管理员
		LoginUser loginUser = LoginUserHolder.getLoginUser();
		Long userId = loginUser.getUserId();
		if (userDao.selectById(userId).getRoleType()!=3){
			throw new FarmException(ResultCodeEnum.ADMIN_ACCESS_FORBIDDEN);
		}

		// 检查用户是否存在
		User existingUser = userDao.selectById(user.getUserId());
		if (existingUser == null) {
			throw new FarmException(ResultCodeEnum.ADMIN_USER_NOT_EXIST);
		}

		// 如果修改了用户名，检查是否已存在
		if (!existingUser.getUsername().equals(user.getUsername())) {
			User checkUser = userDao.selectOneByUsername(user.getUsername());
			if (checkUser != null) {
				throw new FarmException(ResultCodeEnum.ADMIN_USERNAME_ALREADY_EXISTS);
			}
		}

		// 如果修改了密码，则加密
		if (user.getPassword() != null && !user.getPassword().isEmpty()) {
			String encryptedPassword = DigestUtils.md5DigestAsHex(
					user.getPassword().getBytes(StandardCharsets.UTF_8)
			);
			user.setPassword(encryptedPassword);
		} else {
			// 不修改密码时，保持原密码
			user.setPassword(existingUser.getPassword());
		}

		// 更新时间
		user.setUpdateTime(LocalDateTime.now());

		// 更新用户
		return this.updateById(user);
	}

	@Override
	public boolean deleteUser(Long userId) {
		// 查看当前权限是否为管理员
		LoginUser loginUser = LoginUserHolder.getLoginUser();
		Long id = loginUser.getUserId();
		if (userDao.selectById(id).getRoleType()!=3){
			throw new FarmException(ResultCodeEnum.ADMIN_ACCESS_FORBIDDEN);
		}

		// 检查用户是否存在
		User user = userDao.selectById(userId);
		if (user == null) {
			throw new FarmException(ResultCodeEnum.ADMIN_USER_NOT_EXIST);
		}

		// 逻辑删除
		user.setStatus(0);
		return this.updateById(user);
	}

	@Override
	public User getUserById(Long userId) {
		User user = userDao.selectById(userId);
		if (user == null) {
			throw new FarmException(ResultCodeEnum.ADMIN_USER_NOT_EXIST);
		}
		return user;
	}
}